var util = require('./utils/util.js');
var api = require('./config/api.js');
var user = require('./services/user.js');
var Data = require("./utils/data.js");

App({
  onLaunch: function () {
    //初始化当前时间
    // wx.clearStorageSync();
    wx.setStorageSync("startDate", Data.formatDate(new Date(), "yyyy-MM-dd"));
    var tomorrow1 = new Date();
    tomorrow1.setDate((new Date()).getDate() + 1);
    var tomorrow = Data.formatDate(new Date(tomorrow1), "yyyy-MM-dd");
    wx.setStorageSync("endDate", tomorrow);
    //获取用户的登录信息
    user.checkLogin().then(res => {
      console.log('app login')
      this.globalData.userInfo = wx.getStorageSync('userInfo');
      this.globalData.token = wx.getStorageSync('token');
    }).catch(() => {

    });
  },
  onHide: function () {
    //清除推广人id
    wx.removeStorageSync("spreadId");
    // 清除广告显示状态
    wx.removeStorageSync("adShow")
  },
  onShow: function () {
    wx.getLocation({
      success: function (res) {
        var key = 'LD2BZ-GZCLR-DCGWI-WVPJI-XHWMK-7IBDF';
        var url = "https://apis.map.qq.com/ws/geocoder/v1/?location=" + res.latitude + "," + res.longitude + "&coord_type=5&key=" + key;
        util.request(url).then(function (result) {
          console.log(result)
          var city = result.result.address_component.city;
          city = city.replace("市", "");
          wx.setStorageSync("city", city);
        });
      },
    })
  },
  globalData: {
    userInfo: {
      nickname: 'Hi,游客',
      username: '点击去登录',
      avatar: 'http://yanxuan.nosdn.127.net/8945ae63d940cc42406c3f67019c5cb6.png'
    },
    token: '',
    customerId: "",
    openId: "",
    appId: "wx50e880b5aae6fc7d",
    key: "8568c732e8a5cd32e6686be031ecef5c"
  },
  //页面初始化函数
  init: function (options, that, callBack) {
    //初始化城市
    var city = wx.getStorageSync("city");
    var token = wx.getStorageSync("token");
    var type = wx.getStorageSync("type");
    //初始化角色,如果没有登录，默认为普通消费者
    that.setData({
      city: city,
      type: token && token != '' ? type : 2
    })
    let userInfo = wx.getStorageSync('userInfo');
    //初始化注册类型，shareType 0-供应商邀请分销商 1-分销商邀请推广人 2-推广人/供应商/分销商进行分销 3-普通用户分享 -1 为用户自发注册
    var shareType = options.shareType ? options.shareType : "-1";
    wx.setStorageSync("shareType", shareType)
    //判断是否分销
    if (options.shareId && options.shareId != null) {
      //分销，或者邀请注册
      var token = wx.getStorageSync("token")
      //如果没有登录，则使用连接中的
      if(!token){
        wx.setStorageSync("shareId", options.shareId);
        wx.setStorageSync("spreadId", options.spreadId);
        wx.setStorageSync("shareType", options.shareType);
      }
    }
    //执行回调函数
    if (typeof callBack == 'function') {
      callBack();
    }
  },
  //获取分销商信息
  getShareInfo: function (that) {
    var id;
    var customerType = wx.getStorageSync("type");
    if (customerType == '2' || customerType == '3') {

      var data = {
        id: wx.getStorageSync("shareId")
      }
      util.request(api.UserDetail, data).then(function (res) {
        if (res.code === '200') {
          var user = res.datas;
          that.setData({
            shareInfo: res.datas
          })
          wx.setStorageSync("shopName", res.datas.realName)
          wx.setStorageSync("shopPhoto", res.datas.userPhoto)
        }
      });
    } else if (customerType == '1' || customerType == '0') {
      var data = {
        id: wx.getStorageSync("customerId")
      }
      util.request(api.UserDetail, data).then(function (res) {
        if (res.code === '200') {
          that.setData({
            shareInfo: res.datas
          })
          wx.setStorageSync("shopName", res.datas.realName)
          wx.setStorageSync("shopPhoto", res.datas.userPhoto)
        }
      });
    } else {
      //do nothing
    }

  },
  fnShareGoods: function (path, goodsId, imgUrl, goodsName, type, address, price, marketPrice) {
    var that = this;
    address = address?address:"";
    price = price ? price : "";
    //1.判断是否注册
    var customerId = wx.getStorageSync("customerId");
    if (customerId && customerId != null) {
      if (goodsId == null) {
        wx.setStorageSync("isShare", true)
        wx.switchTab({
          url: '/pages/index/index-new',
        })
        return;
      }
      var customerType = wx.getStorageSync("type");
      //判断分销类型
      if (!type || type == "") {
        //如果没有传type，则判断当前用户角色
        if (customerType == '3') {
          //如果用户为普通用户，分销类型为3
          type = "3"
        } else {
          //如果不是普通用户，则为普通分销
          type = "2"
        }
      }
      //已注册

      // //如果用户是分销商或推广人，检查是否认证
      // if ("1" == customerType || "2" == customerType) {
      //   if("1"!=wx.getStorageSync("auth")){
      //     wx.showModal({
      //       title: '还未认证，是否立即去认证？',
      //       content: '',
      //       success:function(options){
      //         if(options.confirm){
      //           wx.navigateTo({
      //             url: '/pages/ucenter/auth/index',
      //           })
      //         }
      //       }
      //     })
      //     return;
      //   }
      // }
      wx.navigateTo({
        url: "/pages/share/index?path=" + path + "&goodsId=" + goodsId + "&imgUrl=" + imgUrl + "&goodsName=" + goodsName + "&type=" + type + "&address=" + address + "&price=" + price + "&marketPrice=" + marketPrice
      })
    } else {
      //没有注册，调用注册方法
      wx.showModal({
        title: '您还未登录，无法分销',
        content: '现在去登录？',
        confirmText: "是",
        cancelText: "否",
        success: function (options) {
          if (options.confirm) {
            wx.navigateTo({
              url: '/pages/auth/register/register',
            })
          }
        }
      })

    }
  },
  showLogin:function(){
    wx.removeStorageSync("token");
    wx.showModal({
      title: '登录过期，请重新登录',
      content: '',
      confirmText: "是",
      cancelText: "否",
      success: function (options) {
        if (options.confirm) {
          wx.navigateTo({
            url: '/pages/auth/register/register',
          })
        }
      }
    })
  }

})